﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using BLL;
using System.Data;
using Model;

public partial class EWM_Erweima : WeiPage
{
    QMActivityBO qbo = new QMActivityBO();
    QMPersonBO qmbo = new QMPersonBO();
    PersonInfoBO pbo = new PersonInfoBO();
    WeiXinRequestBO wbo = new WeiXinRequestBO();
    protected void Page_Load(object sender, EventArgs e)
    {
        //Session["FromUserName"] = "oVKRtuEmDWLI7Vi6MFAd_KVP5b3g";
        string token = Token();
        if (!IsPostBack)
        {
            if (Request.QueryString["code"] != null)
            {
                try
                {
                    string url = string.Format(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + GetAppid() + "&secret=" + GetSecret() + "&code={0}&grant_type=authorization_code", Request.QueryString["code"].ToString());
                    string res = PostRequest(url);
                    if (res.Contains("7200"))
                    {
                        string[] b = res.Split('\"');
                        Session["FromUserName"] = b[13];
                        Session["ToUserName"] = GetAppid();
                    }
                }
                catch (Exception)
                {

                }
            }

            QMPerson qmper = qmbo.GetModel2(Session["FromUserName"].ToString());
            if (qmper != null)
            {
                //string re = "";
                Response.Redirect("wd.aspx?mdname=" + qmper.MdName);
                //AlertMessage("您已领取过");
            }

            DataSet ds = qbo.GetAllList();
            if (ds != null)
            {
                QMActivity qm = new QMActivity();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token;
                    //这里需要修改
                    string d = @"{ ""action_name"": ""QR_LIMIT_SCENE"", ""action_info"": {""scene"": {""scene_id"": {0}}}
        
        }";
                    d = d.Replace("{0}", ds.Tables[0].Rows[i]["MdID"].ToString());
                    string mes = HttpXmlPostRequest(url, d, Encoding.UTF8);
                    //Response.Write(mes);
                    string[] b = mes.Split('\"');
                    string ticket = Server.UrlEncode(b[3]);
                    qm.Id = Convert.ToInt32(ds.Tables[0].Rows[i]["Id"]);
                    qm.CID = Convert.ToInt32(ds.Tables[0].Rows[i]["CID"]);
                    qm.MdID = Convert.ToInt32(ds.Tables[0].Rows[i]["MdID"]);
                    qm.MdName = ds.Tables[0].Rows[i]["MdName"].ToString();
                    qm.Count = ds.Tables[0].Rows[i]["Count"].ToString();
                    qm.Ticket = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;

                    if (ds.Tables[0].Rows[i]["Ticket"].ToString() == "")
                    { 
                        qbo.Update(qm);
                    }                  

                }
            }
        }
    }

    protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlmd.Items.Clear();
        ddlmd.Items.Add(new ListItem("请选择门店", "-1"));
        if (ddlcity.SelectedValue == "上海")
        {
            ddlmd.Items.Add(new ListItem("和平饭店店", "10001"));
            ddlmd.Items.Add(new ListItem("田子坊店", "10002"));
            ddlmd.Items.Add(new ListItem("嘉里店", "10003"));
            ddlmd.Items.Add(new ListItem("虹口龙之梦店", "10004"));
            ddlmd.Items.Add(new ListItem("环球金融店", "10005"));
            ddlmd.Items.Add(new ListItem("米格天地店", "10006"));
        }
        else if (ddlcity.SelectedValue == "北京")
        {
            ddlmd.Items.Add(new ListItem("凯德晶品店", "20001"));
            ddlmd.Items.Add(new ListItem("世贸天阶店", "20002"));
            ddlmd.Items.Add(new ListItem("金地店", "20003"));

        }
        else if (ddlcity.SelectedValue == "成都")
        {
            ddlmd.Items.Add(new ListItem("来福士店", "30001"));
            ddlmd.Items.Add(new ListItem("茂业春熙店", "30002"));
            ddlmd.Items.Add(new ListItem("茂业天地店", "30003"));
        }

    }


    //判断该门店是否可以领取
    protected void ddlmd_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlmd.SelectedValue != "-1")
        {
            int city = 0;
            if (ddlcity.SelectedValue == "上海")
            {
                city = 1;

            }
            else if (ddlcity.SelectedValue == "北京")
            {
                city = 2;

            }
            else if (ddlcity.SelectedValue == "成都")
            {
                city = 3;

            }
            QMActivity qm = qbo.GetModel(city, ddlmd.SelectedItem.ToString());
            DataSet ds = qmbo.GetMD(ddlcity.SelectedValue,ddlmd.SelectedItem.ToString());
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > int.Parse(qm.Count))
                {
                    AlertMessage("本店领取名额已发完，请选择其他门店");

                }
            }
        }

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //Session["FromUserName"] = "oVKRtuEmDWLI7Vi6MFAd_KVP5b3g";
        if (ddlcity.SelectedValue == "-1")
        {
            AlertMessage("请选择城市");
        }
        else if (ddlmd.SelectedValue == "-1")
        {
            AlertMessage("请选择门店");
        }
        if (Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
        {
            string user = Session["FromUserName"].ToString(); //这里需要修改 
            //string user = Request.QueryString["FromUserName"].ToString();
            PersonInfo per = pbo.GetModel(user);
            if (per != null)
            {
                QMPerson qmper= qmbo.GetModel2(user);
                if (qmper != null)
                {
                    Response.Redirect("wd.aspx?mdname=" + qmper.MdName);
                    //AlertMessage("您已领取过");
                }
                else 
                {
                    QMPerson qmperson = new QMPerson();
                    qmperson.City = ddlcity.SelectedValue;
                    qmperson.FromuserName = user;
                    //这里需要修改
                    qmperson.MdKey = int.Parse(ddlmd.SelectedValue);
                    qmperson.MdName = ddlmd.SelectedItem.ToString();
                    qmperson.Status = 0;
                    int count = qmbo.Add(qmperson);
                    if (count > 0)
                    {
                        AlertMessage("领取成功");
                        string Access_token = Token();
                        var postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_token;
                        string d = @"{
    ""touser"":""{0}"",
    ""msgtype"":""text"",
    ""text"":
    {
         ""content"":""您已经获取{1}申领资格，请于5月4号之前到{1}领取。""
    }
}";
                        d = d.Replace("{0}", user).Replace("{1}", ddlmd.SelectedItem.ToString());
                        var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);
                    }
                }

            }
            else
            {
                AlertMessage("请先注册或绑定");

            }
        }
        else 
        {
            AlertMessage("您还未关注雙妹公众账号");
        }

    }


    public void AlertMessage(string message)
    {
        if (message.Equals("请先注册或绑定"))
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");window.location.href='../Spa/weixinreg2.aspx';</script>");
        }
        else if (message.Equals("领取成功"))
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");window.location.href='wd.aspx?mdname=" + ddlmd.SelectedItem.ToString()+"';</script>");

        }

        else
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");</script>");
        }
    }

}